<template>
  <!--  面包屑-->
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item>课程管理</el-breadcrumb-item>
      <el-breadcrumb-item><b>本学期课程</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <!-- 搜索工具 -->
  <div  class="search-container" style="margin: 40px 0 0 0">
    <el-form :inline="true" ref="searchFormRef" :model="searchFormModel" class="demo-form-inline" style="margin-top: 20px">
      <el-form-item prop="cid">
        <el-input v-model="searchFormModel.cid" placeholder="请输入课程号" clearable />
      </el-form-item>
      <el-form-item prop="tid">
        <el-input v-model="searchFormModel.tid" placeholder="请输入教师编号" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchOnSubmit">查询</el-button>
        <el-button  @click="dialogAddState=true" >新增</el-button>
        <el-button
            type="primary"
            @click="toggleLook"
            :disabled="lookStatus.value === '1'"
        >
          开启选课
        </el-button>
        <el-button
            type="danger"
            @click="toggleLook2"
            :disabled="lookStatus.value === '0'"
        >
          关闭选课
        </el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 滚动字幕容器 -->
  <div class="marquee-container">
    <div class="marquee-content">
      所有选修课课程安排在每周公休的时间（每周四下午到晚上），每个班级限额最多35人
    </div>
  </div>

  <!-- 数据表格 -->
  <div style="margin:10px 20px 20px 20px">
    <el-table :data="tableCourse" stripe border style="width: 100%">
      <el-table-column prop="cid" label="课程号"  align="center"/>
      <el-table-column prop="cname" label="课程名" align="center"/>
      <el-table-column prop="tname" label="任课教师" align="center"/>
      <el-table-column prop="ltime" label="上课时间" align="center"/>
      <el-table-column prop="location" label="上课地点" align="center"/>
      <el-table-column prop="chour" label="课时数" align="center"/>
      <el-table-column label="操作" align="center" width="240">
        <template #default="scope">
          <el-button  @click="tableEditHandler(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button
              type="danger"
              @click="tableDeleteHandler(scope.$index, scope.row)">
            结课
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页 -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5,10]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增模态框 -->
  <el-dialog v-model="dialogAddState" title="新建课程" width="400px" @open="dialogAddOnOpen" center>
    <div>
      <el-form ref="formAddRef" :model="formAdd" :rules="addRules" label-width="120px">
<!--        <el-form-item prop="cid" label="课程号">
          <el-input v-model="formAdd.cid" placeholder="请输入课程号，如C001"></el-input>
        </el-form-item>-->
        <el-form-item prop="cname" label="课程名">
          <el-input v-model="formAdd.cname" placeholder="必须含有至少两个字"></el-input>
        </el-form-item>
        <el-form-item prop="tid" label="教师编号">
          <el-select v-model="formAdd.tid" placeholder="请选择教师编号">
            <el-option
                v-for="teacher in teacherList"
                :key="teacher.tid"
                :label="teacher.tid + ' - ' + teacher.tname"
                :value="teacher.tid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="ltime" label="上课时间">
          <el-select v-model="formAdd.ltime" placeholder="请选择上课时间">
            <el-option
                v-for="item in timeOptions"
                :key="item.id"
                :label="item.time"
                :value="item.time">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="location" label="上课地点">
          <el-select v-model="formAdd.location" placeholder="请选择上课地点">
            <el-option
                v-for="item in locationOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="chour" label="课时数">
          <el-select v-model="formAdd.chour" placeholder="请选择课时数">
            <el-option label="21" value="21"></el-option>
            <el-option label="22" value="22"></el-option>
            <el-option label="23" value="23"></el-option>
            <el-option label="24" value="24"></el-option>
            <el-option label="25" value="25"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
  <span class="dialog-footer">
    <el-button @click="dialogAddOnReset">取消</el-button>
    <el-button type="primary" @click="dialogAddOnSubmit">确认</el-button>
  </span>
    </template>
  </el-dialog>

  <!-- 编辑模态框 -->
  <el-dialog v-model="dialogEditState" title="课程信息" width="400px" center>
    <div>
      <el-form ref="formEditRef" :model="formEdit" :rules="editRules" label-width="120px">
        <el-form-item label="课程号">
          {{ formEdit.cid }}
        </el-form-item>
        <el-form-item prop="cname" label="课程名">
          <el-input v-model="formEdit.cname"placeholder="必须含有至少两个字"></el-input>
        </el-form-item>
        <el-form-item label="教师号">
          {{ formEdit.tid }}
        </el-form-item>
        <el-form-item prop="ltime" label="上课时间">
          <el-select v-model="formEdit.ltime" placeholder="请选择上课时间">
            <el-option
                v-for="item in timeOptions"
                :key="item.id"
                :label="item.time"
                :value="item.time">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="location" label="上课地点">
          <el-select v-model="formEdit.location" placeholder="请选择上课地点">
            <el-option
                v-for="item in locationOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="chour" label="课时数">
          <el-select v-model="formEdit.chour" placeholder="请选择课时数">
            <el-option label="21" value="21"></el-option>
            <el-option label="22" value="22"></el-option>
            <el-option label="23" value="23"></el-option>
            <el-option label="24" value="24"></el-option>
            <el-option label="25" value="25"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogEditOnReset">取消</el-button>
        <el-button type="primary" @click="dialogEditOnSubmit">更新</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElDialog } from 'element-plus';
import request from '@/utils/class';
////////////////  开启选课  //////////////////////

// 假设有一个 reactive 引用变量 `lookStatus` 来存储当前是否开启选课
const lookStatus = ref(''); // 初始状态为空，根据后端实际状态进行初始化

// 切换开启/关闭选课状态的方法
const toggleLook = () => {
  const course = { iscanlook: lookStatus.value === '0' ? '1' : '0' };

  request({
    method: 'PUT',
    url: '/course/canlook',
    data: course
  }).then(response => {
    const { errorCode, msg } = response.data;
    if (errorCode === 200) {
      ElMessage.success(msg);
      // 更新状态
      lookStatus.value = course.iscanlook;
    } else {
      ElMessage.error(msg);
    }
  }).catch(error => {
    ElMessage.error('请求失败，无法切换选课状态，请稍后再试');
  });
};

const toggleLook2 = () => {
  const course = { iscanlook: lookStatus.value === '1' ? '0' : '1' };

  request({
    method: 'PUT',
    url: '/course/cantlook',
    data: course
  }).then(response => {
    const { errorCode, msg } = response.data;
    if (errorCode === 200) {
      ElMessage.success(msg);
      // 更新状态
      lookStatus.value = course.iscanlook;
    } else {
      ElMessage.error(msg);
    }
  }).catch(error => {
    ElMessage.error('请求失败，无法切换选课状态，请稍后再试');
  });
};

////////////////  教师下拉框  ////////////////////
//定义一个函数来获取教师列表，并在组件挂载时调用它。
const fetchTeacherList = () => {
  request({
    url: '/teacher/list', // 假设这是获取教师列表的后端接口
    method: 'get',
  }).then((req) => {
    console.log(req)
    if (req.status === 200) {
      // 将教师列表赋值给一个新的响应式变量
      teacherList.value = req.data;
    }
  });
};

// 在onMounted函数中调用fetchTeacherList
onMounted(() => {
  getCourse();
  fetchTeacherList(); // 获取教师列表
});

// 在其他响应式变量定义处添加
const teacherList = ref([]);
/////////////  时间地点下拉框  //////////////////
// 定义上课时间的选项，包括时间段和对应的星期
const timeOptions = ref([
  { id: 1,time: '14:00-15:30'},
  { id: 2,time: '16:00-17:30'},
  { id: 3,time: '19:00-20:30'},
]);

// 定义上课地点的选项
const locationOptions = ref([
  { id: '教室A-301', name: '教室A-301' },
  { id: '教室A-302', name: '教室A-302' },
  { id: '教室A-303', name: '教室A-303' },
  { id: '教室C-301', name: '教室C-301' },
  { id: '教室C-302', name: '教室C-302' },
  { id: '教室C-303', name: '教室C-303' },
  { id: '综合楼-501', name: '综合楼-501' },
  { id: '综合楼-502', name: '综合楼-502' },
  { id: '综合楼-503', name: '综合楼-503' },
]);

//////////////  校验框  ///////////////////
// 校验规则
const addRules = reactive({
 /* cid: [
    {required: true, message: '课程号不能为空', trigger: 'blur'},
    {pattern: /^C\d{3}$/, message: '课程号格式不正确，应以C开头后跟三位数字', trigger: 'blur'}
  ],*/
  cname: [
    {required: true, message: '课程名不能为空', trigger: 'blur'},
    {min: 2, max: 11, message: '课程名长度2-11', trigger: 'blur'},
    {pattern: /^.*[\u4e00-\u9fff]{2,}.*$/, message: '课程名必须包含至少两个汉字', trigger: 'blur'}
  ],
  tid: [
    {required: true, message: '请选择任课教师', trigger: 'change'}
  ],
  ltime: [
    {required: true, message: '请选择上课时间', trigger: 'change'}
  ],
  location: [
    {required: true, message: '请选择上课地点', trigger: 'change'}
  ],
  chour: [
    {required: true, message: '请选择课时数', trigger: 'change'}
  ]
})

const editRules = reactive({
  cname: [
    {required: true, message: '课程名不能为空', trigger: 'blur'},
    {min: 2, max: 11, message: '课程名长度2-11', trigger: 'blur'},
    {pattern: /^.*[\u4e00-\u9fff]{2,}.*$/, message: '课程名必须包含至少两个汉字', trigger: 'blur'}
  ],
 /* tid: [
    {required: true, message: '请选择任课教师', trigger: 'change'}
  ],*/
  ltime: [
    {required: true, message: '请选择上课时间', trigger: 'change'}
  ],
  location: [
    {required: true, message: '请选择上课地点', trigger: 'change'}
  ],
  chour: [
    {required: true, message: '请选择课时数', trigger: 'change'}
  ]
});

////////////////  表格  ///////////////////////
onMounted(()=>{
  getCourse();
})

//表格信息显示
const tableCourse=ref([])
let  totals=ref(0)
const getCourse=()=> {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    // 初始时不包含ID参数
  };

  // 判断是否有搜索条件，如果有，则添加到请求参数中
  if (searchFormModel.cid && searchFormModel.cid.trim() !== '') {
    params.cid = searchFormModel.cid.trim();
  }
  if (searchFormModel.tid && searchFormModel.tid.trim() !== '') {
    params.tid = searchFormModel.tid.trim();
  }

  request({
    url: '/course/all',
    method: 'get',
    params,
  }).then(req => {
    console.log(req)
    console.log(req.data)
    if (200 == req.data.errorCode) {
      tableCourse.value = req.data.data.records;
      totals.value = req.data.data.total;
    }
  })
}

//分页
const currentPage = ref(1)
const pageSize = ref(10)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize.value=val;
  getCourse()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value=val;
  getCourse()
}

//////////////搜索框/////////////////////////
const searchFormRef=ref()

const searchFormModel=reactive({
  cid:''
})

const searchOnSubmit=()=>{
  getCourse();
}

const searchOnReset=()=>{
  searchFormModel.cid=''
}

//////////////  新增模态框相关  ///////////////////////
const dialogAddOnOpen = () => {
  formAddRef.value.resetFields();
};
const dialogAddState = ref(false)

const dialogAddOnSubmit = () => {
  formAddRef.value.validate((valid) => {
    if (valid) {
      // 校验通过，关闭模态框并提交表单
      dialogAddState.value = false;
      request({
        method: 'post',
        url: '/course/add',
        data: formAdd
      }).then(req => {
        if (req.data.errorCode === 200) {
          // 提交成功，刷新课程列表
          getCourse();
          ElMessage({
            type: 'success',
            message: '添加成功'
          });
        } else {
          // 提交失败，显示错误消息
          ElMessage.error('添加失败');
        }
      }).catch(error => {
        // 请求失败，可能是网络问题或其他原因
        ElMessage.error('请求失败');
      });
    } else {
      // 校验失败，显示校验错误消息
      ElMessage.error('表单校验失败');
      return false;
    }
  });
};

const dialogAddOnReset = () => {
  // 清空表单数据
  Object.assign(formAdd , formAddData)
  // 关闭对话框
  dialogAddState.value = false
}

// 新增表单引用
const formAddRef = ref()

// 新增表单初始化数据
const formAddData = {
  cid : '' ,
  cname : '' ,
  tid : '' ,
  ltime : '',
  location :'',
  chour:''
}

// 新增表单绑定数据模型
const formAdd = reactive({...formAddData})   // ...formAddData 解构formAddData

////////////  结课  ///////////////////
const tableDeleteHandler = (rowIndex, rowData) => {
  ElMessageBox.confirm('确认结课 ' + rowData.cname + ' 吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      method: 'get',
      url: '/course/delete/' + rowData.cid
    }).then((req) => {
      if (req.data.errorCode === 200) {
        ElMessage.success('结课成功');
        getCourse(); // 刷新课程列表
      } else {
        ElMessage.error('结课失败');
      }
    });
  }).catch(() => {
    ElMessage.info('已取消结课');
  });
};

//////////////  编辑  ///////////////////////
const tableEditHandler = (rowIndex , rowData) => {
  console.log("-------------")
  console.log(rowIndex)
  console.log(rowData)

  formEdit.cid = rowData.cid
  formEdit.cname = rowData.cname
  formEdit.tid = rowData.tid
  formEdit.ltime = rowData.ltime
  formEdit.location = rowData.location
  formEdit.chour = rowData.chour

  dialogEditState.value = true
}

const dialogEditState = ref(false)

// 编辑对话框的提交处理函数
const dialogEditOnSubmit = () => {
  formEditRef.value.validate((valid) => {
    if (valid) {
      // 校验通过，执行更新操作
      dialogEditState.value = false; // 关闭对话框
      request({
        method: 'PUT',
        url: '/course/update',
        headers: {'content-type': 'application/json;charset=UTF-8'},
        data: JSON.stringify(formEdit)
      }).then(req => {
        if (req.data.errorCode === 200) {
          getCourse(); // 刷新课程列表
          ElMessage.success('更新成功');
        } else {
          ElMessage.error('更新失败');
        }
      }).catch(error => {
        ElMessage.error('请求失败');
      });
    } else {
      // 校验失败，显示错误消息
      ElMessage.error('表单校验失败');
      return false;
    }
  });
};

const dialogEditOnReset = () => {
  // 清空表单数据
  Object.assign(formEdit , formEditData)
  // 关闭对话框
  dialogEditState.value = false
}

// 新增表单引用
const formEditRef = ref()

// 新增表单初始化数据
const formEditData = {
  cid : '' ,
  cname : '' ,
  tid : '' ,
  ltime : '',
  location : '',
  chour : ''
}

// 编辑表单绑定数据模型
const formEdit = reactive({...formEditData})
</script>

<style scoped>
/* 滚动字幕容器样式 */
.marquee-container {
  position: relative;
  overflow: hidden;
  height: 30px;
  background-color: darkgrey;
  color: white;
  padding: 5px;
  box-sizing: border-box;
  white-space: nowrap;
}

/* 滚动内容样式 */
.marquee-content {
  position: absolute;
  white-space: nowrap;
}

/* 创建无限滚动效果 */
.marquee-container::after {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  width: 90%; /* 根据需要调整宽度，确保背景看起来是无限的 */
  background: darkgrey;
  z-index: 1;
}

/* 滚动动画 */
@keyframes marquee {
  0% { transform: translateX(100%); }
  100% { transform: translateX(-100%); }
}

/* 应用滚动动画 */
.marquee-content {
  animation: marquee 15s linear infinite;
  z-index: 2; /* 确保内容在背景之上 */
}

/* 添加自定义模态框样式 */
.custom-dialog {
  border-radius: 10px; /* 圆角边框 */
  /* 其他美化样式 */
}

/* 使按钮居中 */
.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px; /* 根据需要调整外边距 */
}

.el-breadcrumb{
  font-size: 18px;
  margin: 20px;
}
/* 分页居中样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px auto; /* 根据需要调整外边距 */
}
</style>